import QtQuick 2.0

Item {
    id: jiaojie
    width: 575
    height: 70

    property real currentValue: 0
    property real maxValue: 120
    property int scaleCount: 3
    property int scaleLength: 280
    property int scaleWarnLength : 56
    property int scaleWarnLength2 : 0
    property string triangleSource:  "qrc:/imgs/triangle.png"
    property string iconSource
    property string unitName: "℃"

    Image{
        id: leftJiaojieImg
        x: 20
        height: parent.height
        width: parent.height
        source: iconSource
        fillMode: Image.PreserveAspectFit
    }

    Canvas{
        id: canvas
        anchors.left: leftJiaojieImg.right
        anchors.leftMargin: 30
        width: parent.width
        height: parent.height
        contextType: "2d";
        onPaint: {
            var ctx = getContext("2d")
            ctx.reset()

            //绘制刻度值
            for(var i=0; i < scaleCount; i++){
                ctx.save()
                ctx.fillStyle = "white"
                ctx.font = "28px Roboto"
                ctx.textAlign = "center"
                var textX = scaleLength/(scaleCount-1)*i + 7
                var textValue = i / (scaleCount-1) * maxValue
                ctx.fillText(String(textValue), textX, 35)
                ctx.restore()
            }

            drawScale(ctx, 10, scaleLength, "white")

            drawScale(ctx, scaleLength-scaleWarnLength, scaleLength, "#FF5E5E")

            if(scaleWarnLength2 != 0){
                drawScale(ctx, 10, scaleWarnLength2, "#FF5E5E")
            }

            ctx.save()
            var imgX = currentValue / maxValue * scaleLength
            ctx.drawImage(triangleSource, imgX-12, 50)
            ctx.restore()

            ctx.save()
            ctx.fillStyle = "white"
            ctx.font = "46px Aldrich"
            ctx.textAlign = "center"
            ctx.fillText(String(currentValue), scaleLength+80, 50)
            ctx.font = "32px Aldrich"
            ctx.fillText(unitName, scaleLength+140, 50)
            ctx.restore()
        }
        onImageLoaded: requestPaint()
        Component.onCompleted: {
            loadImage(triangleSource)
        }
    }

    function drawScale(ctx, beginX, length, color){
        ctx.save()
        ctx.lineWidth = 10
        ctx.lineCap = "round"
        ctx.strokeStyle = color
        ctx.beginPath()
        ctx.moveTo(beginX, 45)
        ctx.lineTo(length, 45)
        ctx.stroke()
        ctx.restore()
    }


    onCurrentValueChanged:
    {
        if(currentValue > 0 && currentValue > maxValue){
            currentValue = maxValue
        }else if(currentValue < 0 && currentValue < -maxValue){
            currentValue = -maxValue
        }
        canvas.requestPaint()
    }
}
